/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import persistence.entity.Account;
import persistence.entity.Biller;
import persistence.entity.Customer;

/**
 *
 * @author Craig
 */
@Stateless
public class AccountFacade extends AbstractFacade<Account> implements AccountFacadeRemote {

    @PersistenceContext(unitName = "Entity-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public AccountFacade() {
        super(Account.class);
    }

    @Override
    public int getBalance(int accID) {
        Account acc = find(accID);
        if (acc == null) {
            return 0;
        }

        return acc.getAccountBalance();
    }

    @Override
    public List<Integer> getAccounts(int custID, boolean isCust) {
        List<Account> accounts = getAccountList(custID, isCust);
        List<Integer> returnAccIDs = new ArrayList<Integer>();

        for (Account acc : accounts) {
            returnAccIDs.add(acc.getAccountId());
        }
        
        //Used to prevent lazy initilization problem
        System.out.println("Ignore me: " + returnAccIDs.size());
        return returnAccIDs;
    }

    private Integer getCustID(Account acc, boolean isCust) {
        Biller biller = acc.getAccountBillerId();
        Customer customer = acc.getAccountCustomerId();

        if (biller != null && !isCust) {
            return biller.getBillerId();
        } else if (customer != null && isCust) {
            return customer.getCustId();
        }
        return -1;
    }

    @Override
    public List<Account> getAccountList(int custID, boolean isCust) {
        List<Account> accounts = findAll();
        List<Account> returnAccounts = new ArrayList<Account>();

        for (Account acc : accounts) {
            if (getCustID(acc, isCust) == custID) {
                returnAccounts.add(acc);
            }
        }
        return returnAccounts;

    }
}
